package com.huashun.ship.run.shiplock.task;

import com.huashun.ship.run.shiplock.dto.ShipLockOverviewDTO;
import com.huashun.ship.run.shiplock.service.ShipLockService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 船闸相关数据自动任务类
 * @author yzh
 * @version 0.0.1
 * @since 20200510
 */
@Component
@Configuration
@Slf4j
public class ShiplockTask {
    @Autowired
    ShipLockService shipLockService;

    /**
     * 自动拉取船舶过闸数据
     */
    @Scheduled(cron = "0 0/10 * * * ?")
    private void doAutoPullShipLockInfos(){
        log.info("开始自动同步船舶过闸信息。。。。。。");
        long start = (new Date()).getTime();
        try {
            log.debug("Step1：拉取闸口汇总信息。。。。。。");
            shipLockService.reloadShipLockOverviews();
            List<ShipLockOverviewDTO> overviewDTOs = this.shipLockService.getAllShipLockOverviewDTOs();

            //让线程暂停10秒，避免因频繁请求数据导致抓取失败
            try {
                Thread.sleep(10000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            log.debug("Step2：遍历各闸口拉取上行和下行的明细数据。。。。。。");
            for (int i = 0; i < overviewDTOs.size(); i++){
                ShipLockOverviewDTO dto = overviewDTOs.get(i);
                if (dto.getShipLockCode() != null && dto.getShipLockCode().trim().length() > 0){
                    this.shipLockService.reloadShipLockDetails(dto.getShipLockCode(), "up");
                    this.shipLockService.reloadShipLockDetails(dto.getShipLockCode(), "down");
                }
            }
            log.info("船舶过闸数据同步完毕，本次共同步了" + overviewDTOs.size() + "个船闸的过闸信息，用时" + ((new Date()).getTime() - start) + "毫秒");
        } catch (IOException e) {
            log.error("自动同步船舶过闸数据时遇到IO错误，请检查西江水运物流信息网是否可以正常访问。");
            e.printStackTrace();
        }
    }
}
